import { OauthClientDetailsType } from '@/datatypes/oauthClientDetails/data';
import { handleAdd, handleRemove, handleUpdate, page, remove } from '@/services';
import { EyeInvisibleOutlined, EyeOutlined, PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProFormSelect,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components';

import { AuthModeValueEnum, GrantType } from '@/enums/auth';
import { generateValueEnum, getTenantOptions, useTenants } from '@/hooks/useTenants';
import AddPermForm from '@/pages/tenant/oauthClientDetails/components/AddPermForm';
import UpdateForm from '@/pages/tenant/oauthClientDetails/components/UpdateForm';
import { login } from '@/services/user';
import { OauthClientDetailsPermissionUrl, OauthClientDetailsUrl } from '@/urls';
import { Button, Drawer, message, Tag } from 'antd';
import React, { useRef, useState } from 'react';

const TableList: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<OauthClientDetailsType>();
  const [selectedRowsState, setSelectedRows] = useState<OauthClientDetailsType[]>([]);
  const [hiddenState, setHiddenState] = useState<Record<string, boolean>>({});

  const tenants = useTenants();
  const tenantOptions = getTenantOptions(tenants);

  const [addPermModalVisible, handleAddPermModalVisible] = useState<boolean>(false);

  const columns: ProColumns<OauthClientDetailsType>[] = [
    {
      title: 'Client ID',
      dataIndex: 'clientId',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: 'Client Secret',
      dataIndex: 'clientSecret',
      hideInSearch: true,
      width: 200,
      render: (text: React.ReactNode, entity: OauthClientDetailsType) => {
        const isHidden = hiddenState[entity.clientId] ?? true;

        const toggleVisibility = () => {
          setHiddenState({
            ...hiddenState,
            [entity.clientId]: !isHidden,
          });
        };

        return (
          <div>
            {isHidden ? <span>********</span> : <span>{text}</span>}
            <span onClick={toggleVisibility} style={{ marginLeft: 8 }}>
              {isHidden ? <EyeOutlined /> : <EyeInvisibleOutlined />}
            </span>
          </div>
        );
      },
    },
    {
      title: 'AccessToken有效期',
      dataIndex: 'accessTokenValidity',
      hideInSearch: true,
    },
    {
      title: 'RefreshToken有效期',
      dataIndex: 'refreshTokenValidity',
      hideInSearch: true,
    },
    {
      title: '附加信息',
      dataIndex: 'additionalInformation',
      hideInSearch: true,
    },
    {
      title: '租户',
      dataIndex: 'tenantId',
      render: (value: React.ReactNode) => {
        const selectedTenant = tenantOptions.find((option: any) => option.value === value);
        return selectedTenant ? selectedTenant.label : value;
      },
      valueEnum: generateValueEnum(tenants),
    },
    {
      title: '认证模式',
      dataIndex: 'authorizedGrantTypes',
      hideInSearch: true,
      render: (text: React.ReactNode) => {
        if (!text) return null;
        const tags = (text as string).split(',').map((tag) => (
          <Tag key={tag} color="blue">
            {AuthModeValueEnum[tag] || tag}
          </Tag>
        ));
        return <>{tags}</>;
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="update"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
            setShowDetail(false);
          }}
        >
          更新
        </a>,
        record.authorizedGrantTypes?.includes(GrantType.ClientCredentials) ? (
          <a
            key="login"
            onClick={async () => {
              const { clientId, clientSecret, tenantId } = record;
              const { success, msg, data } = await login({
                client_id: clientId,
                client_secret: clientSecret,
                grant_type: GrantType.ClientCredentials,
                tenantId,
              });
              if (success) {
                message.success(`${data.access_token}`);
              } else {
                message.error(msg);
              }
            }}
          >
            登录
          </a>
        ) : (
          ''
        ),
        record.authorizedGrantTypes?.includes(GrantType.ClientCredentials) ? (
          <a
            key="auth"
            onClick={() => {
              handleAddPermModalVisible(true);
              setCurrentRow(record);
              setShowDetail(false);
            }}
          >
            授权
          </a>
        ) : (
          ''
        ),
        <a
          key="remove"
          onClick={async () => {
            await handleRemove(OauthClientDetailsUrl, record.clientId);
            if (actionRef.current) {
              await actionRef.current.reload();
            }
            setShowDetail(false);
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<OauthClientDetailsType, API.PageParams>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="clientId"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(params) => page(OauthClientDetailsUrl, params)}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              selectedRowsState.map(async (e) => {
                await remove(OauthClientDetailsUrl, e.clientId);
              });
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        title="新建"
        width="400px"
        open={createModalVisible}
        onOpenChange={handleModalVisible}
        onFinish={async (value: any) => {
          const authorizedGrantTypes = value.authorizedGrantTypes.join(',');
          const formData = {
            ...value,
            authorizedGrantTypes,
          };
          const success = await handleAdd(
            OauthClientDetailsUrl,
            formData as OauthClientDetailsType,
          );
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              await actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          name="clientId"
          label="Client ID"
          placeholder="请输入ClientID"
          rules={[
            {
              required: true,
              message: 'ClientID为必填项',
            },
          ]}
        />
        <ProFormText
          name="clientSecret"
          label="Client Secret"
          placeholder="请输入ClientSecret"
          rules={[
            {
              required: true,
              message: 'ClientSecret为必填项',
            },
          ]}
        />
        <ProFormSelect
          name="authorizedGrantTypes"
          label="认证模式"
          placeholder="请选择认证模式"
          mode="multiple"
          valueEnum={AuthModeValueEnum}
          rules={[
            {
              required: true,
              message: '认证模式为必填项',
            },
          ]}
        />
        <ProFormText
          name="accessTokenValidity"
          label="AccessToken有效期"
          placeholder="请输入AccessToken有效期（秒）"
          rules={[
            {
              required: true,
              message: 'AccessToken有效期为必填项',
            },
          ]}
        />
        <ProFormText
          name="refreshTokenValidity"
          label="RefreshToken有效期"
          placeholder="请输入RefreshToken有效期（秒）"
          rules={[
            {
              required: true,
              message: 'RefreshToken有效期为必填项',
            },
          ]}
        />
        <ProFormText name="additionalInformation" label="附加信息" placeholder="请输入附加信息" />
      </ModalForm>
      <UpdateForm
        onSubmit={async (value) => {
          const success = await handleUpdate(OauthClientDetailsUrl, value, currentRow);

          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              await actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />
      <AddPermForm
        onSubmit={async (value) => {
          const permissionIds = value?.targetKeys;
          const clientId = currentRow?.clientId;
          const success = await handleAdd(OauthClientDetailsPermissionUrl, {
            permissionIds,
            clientId,
          });

          if (success) {
            handleAddPermModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              await actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleAddPermModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={addPermModalVisible}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.clientId && (
          <ProDescriptions<OauthClientDetailsType>
            column={2}
            title={currentRow?.clientId}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.clientId,
            }}
            columns={columns as ProDescriptionsItemProps<OauthClientDetailsType>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
